#Data : 225-3-13
#Author : Fengyuan Zhang (Franklin)
#Email : franklinzhang@foxmail.com

import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from torch_geometric.datasets import Planetoid
import torch.optim as optim

# 定义一个两层的GCN模型
class GCN(torch.nn.Module):
    def __init__(self, input_dim, hidden_dim, num_classes):
        super(GCN, self).__init__()
        # 第一层图卷积，将输入特征映射到hidden_dim维度
        self.conv1 = GCNConv(input_dim, hidden_dim)
        # 第二层图卷积，将hidden_dim映射到类别数
        self.conv2 = GCNConv(hidden_dim, num_classes)

    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        # 第一层卷积 + ReLU激活
        x = self.conv1(x, edge_index)
        x = F.relu(x)
        # dropout防止过拟合
        x = F.dropout(x, training=self.training)
        # 第二层卷积 + log_softmax输出概率分布
        x = self.conv2(x, edge_index)
        return F.log_softmax(x, dim=1)


# 定义训练函数
def train():
    model.train()
    optimizer.zero_grad()
    out = model(data)
    # 仅计算训练集上的损失
    loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
    loss.backward()
    optimizer.step()
    return loss.item()

# 定义测试函数
def test():
    model.eval()
    logits, accs = model(data), []
    for mask in [data.train_mask, data.val_mask, data.test_mask]:
        pred = logits[mask].max(1)[1]
        acc = pred.eq(data.y[mask]).sum().item() / mask.sum().item()
        accs.append(acc)
    return accs

# 加载Cora数据集
dataset = Planetoid(root='/tmp/Cora', name='Cora')
data = dataset[0]

# 设置设备：如果有GPU则使用GPU，否则使用CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = GCN(dataset.num_features, hidden_dim=16, num_classes=dataset.num_classes).to(device)
data = data.to(device)
optimizer = optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

# 进行多轮训练
for epoch in range(1, 201):
    loss = train()
    train_acc, val_acc, test_acc = test()
    if epoch % 10 == 0:
        print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}, Train Acc: {train_acc:.4f}, Val Acc: {val_acc:.4f}, Test Acc: {test_acc:.4f}')
